package sse

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/google/uuid"
)

// ChatStatus 聊天状态枚举（前端专用）
type ChatStatus = ResponseStatus

// StreamEvent 统一的流事件格式
type StreamEvent struct {
	ConversationID uuid.UUID `json:"conversation_id"`
	Timestamp      int64     `json:"timestamp"`

	// 聊天相关字段
	Status                ChatStatus `json:"status,omitempty"`
	Content               string     `json:"content,omitempty"`
	ReasoningContent      string     `json:"reasoning_content,omitempty"`
	DeltaContent          string     `json:"delta_content,omitempty"`
	DeltaReasoningContent string     `json:"delta_reasoning_content,omitempty"`
	StatusMessage         string     `json:"status_message,omitempty"`
	Error                 *ErrorInfo `json:"error,omitempty"`
}

// NewChatEvent 创建聊天事件
func NewChatEvent(conversationID uuid.UUID, status ChatStatus) *StreamEvent {
	return &StreamEvent{
		ConversationID: conversationID,
		Timestamp:      time.Now().UnixMilli(),
		Status:         status,
	}
}

// WithContent 设置内容
func (e *StreamEvent) WithContent(content string) *StreamEvent {
	e.Content = content
	return e
}

// WithDeltaContent 设置增量内容
func (e *StreamEvent) WithDeltaContent(deltaContent string) *StreamEvent {
	e.DeltaContent = deltaContent
	return e
}

// WithReasoningContent 设置推理内容
func (e *StreamEvent) WithReasoningContent(reasoning string) *StreamEvent {
	e.ReasoningContent = reasoning
	return e
}

// WithDeltaReasoningContent 设置增量推理内容
func (e *StreamEvent) WithDeltaReasoningContent(deltaReasoning string) *StreamEvent {
	e.DeltaReasoningContent = deltaReasoning
	return e
}

// WithStatusMessage 设置状态消息
func (e *StreamEvent) WithStatusMessage(message string) *StreamEvent {
	e.StatusMessage = message
	return e
}

// WithError 设置错误信息
func (e *StreamEvent) WithError(code, message, details string, retry bool) *StreamEvent {
	e.Status = StatusError
	e.Error = &ErrorInfo{
		Code:    code,
		Message: message,
		Details: details,
		Retry:   retry,
	}
	return e
}

// ToJSON 转换为JSON字符串
func (e *StreamEvent) ToJSON() (string, error) {
	data, err := json.Marshal(e)
	if err != nil {
		return "", err
	}
	return string(data), nil
}

// ToSSEData 转换为SSE格式的数据
func (e *StreamEvent) ToSSEData() (string, error) {
	jsonData, err := e.ToJSON()
	if err != nil {
		return "", err
	}
	// 添加事件类型以改进前端解析
	eventType := "message"
	switch e.Status {
	case StatusError:
		eventType = "error"
	case StatusCompleted:
		eventType = "complete"
	}
	return fmt.Sprintf("event: %s\ndata: %s\n\n", eventType, jsonData), nil
}
